package com.magirard.project.texture 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.geom.Matrix;
	public class TextureManager 
	{		
		public function TextureManager() 
		{
			
		}
		
		public static function CreateTextureWithMipMap(aContext3d:Context3D, aTextureData:Bitmap):Texture
		{

			var ws:int = aTextureData.bitmapData.width;
			var hs:int = aTextureData.bitmapData.height;
			
			if (!IsPowerOfTwo(ws) || !IsPowerOfTwo(hs))
			{
				trace("ERROR :: texture size is not a power of 2");
				return null;
			}
			var texture:Texture = aContext3d.createTexture(ws, hs, Context3DTextureFormat.BGRA, false);
			var level:int = 0;
			var tmp:BitmapData = new BitmapData(ws, hs, true, 0x00000000);
			var transform:Matrix = new Matrix();
			while (ws >= 1 && hs >= 1)
			{
				tmp.draw(aTextureData.bitmapData, transform, null, null, null, true);
				texture.uploadFromBitmapData(tmp, level);
				transform.scale(0.5, 0.5);
				level++;
				hs >>= 1;
				ws >>= 1;
				if (hs && ws)
				{
					tmp.dispose();
					trace(level, ws, hs);
					tmp = new BitmapData(ws, hs, true, 0x00000000);
				}
			}
			tmp.dispose();
			return texture;
		}
		
		private static function IsPowerOfTwo(aSize:int):Boolean 
		{
			return ((aSize & (aSize - 1)) == 0);
		}
		
	}

}